import { MinusCircleOutlined } from '@ant-design/icons-vue'
import {
  Button,
  Form,
  FormItem,
  Input,
  InputNumber,
  message,
  Select,
  SelectOption,
  Spin
} from 'ant-design-vue'
import { forEach } from 'lodash-es'
import { render } from 'nprogress'
import { defineComponent, onMounted, ref } from 'vue'

import { commonApi } from '@/apis'
import { ExpressTempleteItem } from '@/apis/jindouGiftTypes'
import qzyApi from '@/apis/qzyApi'
import { qzySettingItem } from '@/apis/qzyType'
import { ProEditor, ProEditorProps, ProEditorRef } from '@/components'
import UploadFile from '@/components/UploadFile'
import { isValueEmpty } from '@/utils'

export default defineComponent({
  name: 'QzyLotterySetting',
  setup() {
    const loading = ref(true)
    const optionItemCur = ref({
      itemVoList: [{}, {}, {}],
      card: { settingType: 6 },
      newUserSettings: { settingType: 4 },
      rules: { settingType: 5 }
    } as any)
    const serviceProviderLevel = ref()
    function add() {
      optionItemCur.value.itemVoList.push({})
    }

    const editorRef = ref({} as ProEditorRef)
    const editorConfig = ref({
      wrapStyle: {
        width: '702px'
      },
      editorStyle: {
        height: '400px'
      },
      editorHtml: '',
      editorVisible: false,
      editorConfig: {
        MENU_CONF: {
          uploadImage: {
            server: commonApi.uploadFileUrl,
            fieldName: 'file',
            customInsert(res: any, insertFn: any) {
              // res 即服务端的返回结果
              const url = res.data
              // 从 res 中找到 url alt href ，然后插图图片
              insertFn(url, '', '')
            },
            maxFileSize: 10 * 1024 * 1024,
            onError(file: File, err: any, res: any) {
              if (file && file.size > 10 * 1024 * 1024) {
                message.error('图片超过10M，请压缩图片或分段上传')
              }
            }
          }
        } as any
      },
      toolbarConfig: {
        excludeKeys: ['group-video']
      }
    } as ProEditorProps)

    onMounted(() => {
      getDetail()
    })
    //获取详情
    async function getDetail() {
      loading.value = true
      try {
        const respData = await qzyApi.drawSettingDetail()
        if (!isValueEmpty(respData.itemVoList)) {
          optionItemCur.value = respData
        }
        editorConfig.value.editorHtml = optionItemCur.value.rules.content
        editorConfig.value.editorVisible = true
      } finally {
        loading.value = false
      }
    }
    const test = ref('')
    function getSelect(value, index) {
      console.log(value)
      if (value === 3) {
        optionItemCur.value.itemVoList[index].num = 1
        optionItemCur.value.itemVoList[index].drawNum = 1
      }
    }

    //保存
    async function handleConfirm() {
      optionItemCur.value.rules.content = editorRef.value.editor.getHtml()
      // 任务配置限制
      let i = 0,
        a = 0,
        b = 0,
        p = 0
      optionItemCur.value.itemVoList.forEach(element => {
        if (element.settingType === 0) {
          p = p + 1
        }
        if (element.settingType === 1) {
          i = i + 1
        }
        if (element.settingType === 2) {
          a = a + 1
        }
        if (element.settingType === 3) {
          b = b + 1
        }
      })
      if (p > 3) {
        message.error('上称只能配置三项')
        return
      }
      if (i >= 2) {
        message.error('防伪认证只能配置一项')
        return
      }
      if (a >= 2) {
        message.error('照片素材只能配置一项')
        return
      }
      if (b >= 2) {
        message.error('邀请新人只能配置一项')
        return
      }
      //保存限制
      let flag = 0
      optionItemCur.value.itemVoList.forEach(element => {
        if (isValueEmpty(element)) {
          flag = flag + 1
        }
        if (element.settingType === 0) {
          if (
            isValueEmpty(element.drawNum) ||
            isValueEmpty(element.num) ||
            isValueEmpty(element.timeType) ||
            isValueEmpty(element.winningProbability)
          ) {
            flag = flag + 1
          }
        }
        if (element.settingType === 1 || element.settingType === 2) {
          if (
            isValueEmpty(element.drawNum) ||
            isValueEmpty(element.winningProbability)
          ) {
            flag = flag + 1
          }
        }
      })
      if (flag > 0) {
        message.error('请确认设置填写完整')
        return
      }
      console.log(optionItemCur.value.rules)
      if (
        optionItemCur.value.newUserSettings.drawNum == null ||
        optionItemCur.value.newUserSettings.winningProbability == null
      ) {
        message.error('请确认设置填写完整')
        return
      }
      try {
        await qzyApi
          .drawSetting({
            card: optionItemCur.value.card,
            itemCommandList: optionItemCur.value.itemVoList,
            newUserSettings: optionItemCur.value.newUserSettings,
            rules: optionItemCur.value.rules
          })
          .then(() => message.success('保存成功'))
      } finally {
      }
    }

    return {
      optionItemCur,
      editorConfig,
      serviceProviderLevel,
      editorRef,
      test,
      loading,
      handleConfirm,
      getSelect,
      add
    }
  },
  render() {
    return (
      <Spin spinning={this.loading}>
        <Form>
          <FormItem label={'任务'}>
            {this.optionItemCur.itemVoList?.map((k, index) => (
              <div style={{ marginBottom: '15px' }}>
                <Select
                  v-model:value={k.settingType}
                  style={{ width: '100px', marginRight: '45px' }}
                  placeholder="请选择"
                  onChange={() => this.getSelect(k.settingType, index)}
                >
                  <SelectOption value={0}>{`上称打卡`}</SelectOption>
                  <SelectOption value={1}>{`防伪认证`}</SelectOption>
                  <SelectOption value={2}>{`照片素材`}</SelectOption>
                  <SelectOption value={3}>{`邀请新人`}</SelectOption>
                </Select>
                <span v-show={k.settingType === 0}>
                  <Select
                    v-model:value={k.timeType}
                    style={{ width: '80px', marginRight: '10px' }}
                  >
                    <SelectOption value={0}>{`每日`}</SelectOption>
                    <SelectOption value={1}>{`每周`}</SelectOption>
                    <SelectOption value={2}>{`每月`}</SelectOption>
                  </Select>
                  {`上称打卡满`}
                  <InputNumber
                    v-model:value={k.num}
                    min={0}
                    precision={0}
                    style={{
                      width: '60px',
                      marginLeft: '10px',
                      marginRight: '10px'
                    }}
                  ></InputNumber>
                  {`次,`}
                  {` 获得`}
                  <InputNumber
                    v-model:value={k.drawNum}
                    min={0}
                    precision={0}
                    style={{
                      width: '60px',
                      marginLeft: '10px',
                      marginRight: '10px'
                    }}
                  ></InputNumber>
                  {`次抽奖机会`}
                  <span style={{ marginLeft: '50px' }}>
                    中奖概率
                    <InputNumber
                      v-model:value={k.winningProbability}
                      style={{
                        marginLeft: '10px',
                        marginRight: '10px'
                      }}
                      min={0}
                      formatter={value => `${value}%`}
                      parser={value => value.replace('%', '')}
                    ></InputNumber>
                  </span>
                </span>
                <span v-show={k.settingType === 1}>
                  {`扫码验真伪，正品获得`}
                  <InputNumber
                    v-model:value={k.drawNum}
                    precision={0}
                    min={0}
                    style={{
                      width: '60px',
                      marginLeft: '10px',
                      marginRight: '10px'
                    }}
                  ></InputNumber>
                  {`次抽奖机会`}
                  <span style={{ marginLeft: '199px' }}>
                    中奖概率
                    <InputNumber
                      v-model:value={k.winningProbability}
                      min={0}
                      style={{
                        marginLeft: '10px',
                        marginRight: '10px'
                      }}
                      formatter={value => `${value}%`}
                      parser={value => value.replace('%', '')}
                    ></InputNumber>
                  </span>
                </span>
                <span v-show={k.settingType === 2}>
                  {`每日上传照片素材,获得`}
                  <InputNumber
                    v-model:value={k.drawNum}
                    min={0}
                    precision={0}
                    style={{
                      width: '60px',
                      marginLeft: '10px',
                      marginRight: '10px'
                    }}
                  ></InputNumber>
                  {`次抽奖机会`}
                  <span style={{ marginLeft: '196px' }}>
                    中奖概率
                    <InputNumber
                      v-model:value={k.winningProbability}
                      min={0}
                      style={{
                        marginLeft: '10px',
                        marginRight: '10px'
                      }}
                      formatter={value => `${value}%`}
                      parser={value => value.replace('%', '')}
                    ></InputNumber>
                  </span>
                </span>
                <span v-show={k.settingType === 3}>
                  {`每成功邀请`}
                  <InputNumber
                    disabled
                    v-model:value={k.num}
                    min={0}
                    precision={0}
                    style={{
                      width: '60px',
                      marginLeft: '10px',
                      marginRight: '10px'
                    }}
                  ></InputNumber>
                  {`个新人,获得`}
                  <InputNumber
                    v-model:value={k.drawNum}
                    min={0}
                    disabled
                    precision={0}
                    style={{
                      width: '60px',
                      marginLeft: '10px',
                      marginRight: '10px'
                    }}
                  ></InputNumber>
                  {`抽奖机会`}
                  <span style={{ marginLeft: '129px' }}>
                    中奖概率
                    <InputNumber
                      v-model:value={k.winningProbability}
                      min={0}
                      style={{
                        marginLeft: '10px',
                        marginRight: '10px'
                      }}
                      formatter={value => `${value}%`}
                      parser={value => value.replace('%', '')}
                    ></InputNumber>
                  </span>
                </span>
                <MinusCircleOutlined
                  style={{ marginLeft: '10px' }}
                  onClick={() => this.optionItemCur.itemVoList.splice(index, 1)}
                />
              </div>
            ))}
            <Button
              onClick={this.add}
              style={{
                marginTop: '15px',
                width: '140px',
                height: '40px',
                marginBottom: '15px'
              }}
              type="primary"
            >
              添加任务
            </Button>
            <span style={{ color: '#aaaaaa' }}>
              （注：照片素材、邀请新人、防伪认证只能有一项配置）
            </span>
          </FormItem>
          <FormItem style={{ marginBottom: '50px' }}>
            新用户设置：{`新用户注册赠送`}
            <InputNumber
              v-model:value={this.optionItemCur.newUserSettings.drawNum}
              precision={0}
              min={0}
              style={{
                width: '60px',
                marginLeft: '10px',
                marginRight: '10px'
              }}
            ></InputNumber>
            {`次抽奖机会`}
            <span style={{ marginLeft: '50px' }}>
              中奖概率
              <InputNumber
                min={0}
                v-model:value={
                  this.optionItemCur.newUserSettings.winningProbability
                }
                style={{
                  marginLeft: '10px',
                  marginRight: '10px'
                }}
                formatter={value => `${value}%`}
                parser={value => value.replace('%', '')}
              ></InputNumber>
            </span>
          </FormItem>
          <FormItem label="规则文案：">
            <ProEditor
              style={{ width: '720px', height: '500px' }}
              ref="editorRef"
              {...this.editorConfig}
            />
          </FormItem>
          <FormItem label="分享小卡片设置：" style={{ marginTop: '30px' }}>
            <div style={{ marginBottom: '30px' }}>
              邀请好友分享文案：
              <Input
                style={{ width: '250px' }}
                v-model:value={this.optionItemCur.card.content}
              ></Input>
            </div>
            <FormItem>
              <UploadFile v-model={[this.optionItemCur.card.imgUrl, 'urls']}>
                上传图片
              </UploadFile>
              <div style={{ color: '#aaaaaa' }}>
                用于邀请好友分享的卡片背景设置，尺寸500*400
              </div>
            </FormItem>
            <FormItem>
              <div>
                赠送碎片分享文案：
                <Input
                  style={{ width: '250px' }}
                  v-model:value={this.optionItemCur.card.contentExt}
                ></Input>
              </div>
            </FormItem>
          </FormItem>

          <FormItem style={{ marginLeft: '550px', marginTop: '20px' }}>
            <Button
              type="primary"
              style={{ width: '260px', height: '45px' }}
              onClick={this.handleConfirm}
            >
              保存
            </Button>
          </FormItem>
        </Form>
      </Spin>
    )
  }
})
